//
//  FXTabBar.swift
//  微博(Swift)
//
//  Created by V on 15/12/26.
//  Copyright © 2015年 V. All rights reserved.
//

import UIKit

class FXTabBar: UITabBar {
    
    // 撰写按钮点击实现的闭包
    var composeButtonClickClourse: (() -> ())?
    
    
   
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundImage = UIImage(named: "tabbar_background")
        addSubview(composeButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: - 懒加载控件
    // private 是私有，如果不想把某些属性或者方法暴露给外界，那么就可以使用其修饰
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        // 设置 button 的状态图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Selected)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Selected)
        // 设置大小
        button.sizeToFit()
        // 添加单击事件
        button.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchUpInside)
        return button
    }()
    
    
    
    // MARK: - 撰写按钮点方法实现
    @objc private func composeButtonClick(){
        composeButtonClickClourse?()
    }
    
    
    // MARK: - 布局子控件
    override func layoutSubviews() {
        super.layoutSubviews()
        // 调整按钮的位置
        composeButton.center.x = bounds.size.width * 0.5
        composeButton.center.y = bounds.size.height * 0.5
        // 调整底部 4 个按钮的位置
        let chilW = bounds.size.width * 0.2
        var index = 0
        for value in subviews {
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                value.frame.size.width = chilW
                value.frame.origin.x = CGFloat(index) * chilW
                index++
                if index == 2 {
                    index++
                }
            }
        }
        // print("-----")
    }

}
